<?php
namespace app\jobmanagement\service;


use app\model\TaskWork as TaskWorkModel;
use app\model\TaskTask as TaskTaskModel;
use app\model\Settle as SettleModel;
use app\model\Product as ProductModel;
use app\model\ProductWork as ProductWorkModel;
use app\model\User as UserModel;
use app\model\Capital as CapitalModel;

use app\lib\Dingtalk as DingtalkLib;

use app\jobmanagement\service\Common as CommonService;
use app\jobmanagement\service\TransferConfig as TransferConfigService;

use think\Db;
use think\Model;

class User extends Model
{

    protected $dd_user_id;

    protected $mTask;

    protected $mTaskWork;

    protected $mSettle;

    protected $mUser;

    protected $mCapital;

    protected $capital_type;

    protected $capital_status;

    protected $DingtalkService;

    public function __construct($data = [])
    {
        parent::__construct($data);
        $this->dd_user_id = session('dd_user_id');
        $this->capital_type = config('dic.capital_type');
        $this->capital_status = config('dic.capital_status');
        $this->mTask = new TaskTaskModel();
        $this->mTaskWork = new TaskWorkModel();
        $this->mSettle = new SettleModel();
        $this->mUser = new UserModel();
        $this->mCapital = new CapitalModel();
        $this->DingtalkService = new DingtalkLib();
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 15:38
     * @description 获取用户资金情况
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWorkerCapital()
    {
        if (!$this->dd_user_id) {
            return [];
        }
        $user = $this->mUser
            ->where(['dd_user_id' => $this->dd_user_id])
            ->find();
        if (empty($user)) {
            // 再去钉钉查询一次
            $user_info = $this->DingtalkService->getUserInfoByDDUserId($this->dd_user_id);
            if (empty($user_info)) {
                return [];
            } else {
                $new_user = [
                    'dd_user_id' => $this->dd_user_id,
                    'name' => $user_info['name'],
                    'avatar' => $user_info['avatar'],
                    'level' => 1,
                ];
                $res = $this->mUser->insert($new_user);
                if ($res) {
                    return [
                        'total' => 0,
                        'freeze' => 0,
                        'usable' => 0,
                        'account_code' => '',
                        'account_user' => '',
                        'dd_user_id' => $this->dd_user_id,
                    ];
                } else {
                    return [];
                }
            }

        } else {
            // 查询到用户资金-再查询是否有 正在申请提现的
            $num = $this->mCapital
                ->where(['dd_user_id' => $this->dd_user_id, 'status' => 2])
                ->field('sum(amount) as amount')
                ->find();
            if (empty($num)) {
                $freeze = 0;
            } else {
                $freeze = $num['amount'] ? $num['amount'] : 0;
            }
            $total = $user['capital'];
            $usable = $total > $num['amount'] ? ($total - $num['amount']) : 0;
            $total = sprintf("%.2f", $total);
            $freeze = sprintf("%.2f", $freeze);
            $usable = sprintf("%.2f", $usable);
            return [
                'total' => $total,
                'freeze' => $freeze,
                'usable' => $usable,
                'account_code' => $user['account_code'],
                'account_user' => $user['account_user'],
                'dd_user_id' => $user['dd_user_id'],
            ];
        }

    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 15:46
     * @description 获取用户操作资金记录
     * @param array $param 相关参数
     * @return array|bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWorkerCapitalLog($param = [])
    {
        if (!$this->dd_user_id) {
            return [];
        }
        $user = $this->mUser
            ->where(['dd_user_id' => $this->dd_user_id])
            ->find();
        if (empty($user)) {
            return [];
        }
        $page = $param['page'] > 1 ? $param['page'] : 1;
        $offset =  ($page - 1) * PAGE_SIZE;
        $where = [];
        // 添加年度和月度的信息显示
        if ($param['year']) {
            $year = intval($param['year']);
            if ($year) {
                $where['create_time'] = ['like', $year . '-%'];
            }
        }
        if ($param['year'] && $param['month']) {
            $year = intval($param['year']);
            $month = intval($param['month']);
            $month = str_pad($month, 2, 0, STR_PAD_LEFT);
            if ($year) {
                $where['create_time'] = ['like', $year . '-' . $month . '-%'];
            }
        }
        $list = $this->mCapital
            ->where(['dd_user_id' => $this->dd_user_id])
            ->where($where)
            ->limit($offset, PAGE_SIZE)
            ->order('id desc')
            ->select();
        if (empty($list)) {
            return [];
        } else {
            $box = [];
            $capital_type = $this->capital_type;
            $capital_status = $this->capital_status;
            foreach ($list as $item) {
                $temp = $item->toArray();
                $box[] = [
                    'id' => $temp['id'],
                    'amount' => $temp['amount'],
                    'type' => $temp['type'],
                    'type_name' => $capital_type[$temp['type']],
                    'status' => $temp['status'],
                    'status_name' => $capital_status[$temp['status']],
                    'create_time' => $temp['create_time'],
                    'create_user' => get_user_name($temp['create_user']),
                    'update_remark' => $temp['update_remark'],
                    'update_file' => $temp['update_file'],
                ];
            }
            return $box;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/6/8 11:32
     * @description 获取月度数据统计
     * @param array $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWorkerCapitalMonthCensus($param = [])
    {
        if (!$this->dd_user_id) {
            return [];
        }
        $user = $this->mUser
            ->where(['dd_user_id' => $this->dd_user_id])
            ->find();
        if (empty($user)) {
            return [];
        }
        $page = $param['page'] > 1 ? $param['page'] : 1;
        // 往前推12个月
        if ($page < 2) {
            $end_month = date('Y-m');
        } else {
            $now_date = date('Y-m');
            $tip = $now_date . ' -'. ($page - 1) . ' year';
            $end_month = date('Y-m', $tip);
        }
        // 添加年度和月度的信息显示
        $list = [];
        for ($m = 0; $m < 12; $m++) {
            if ($m == 0) {
                $month = $end_month . '-%';
            } else {
                $em = $end_month . ' -' . $m . ' month';
                $eve = date('Y-m', strtotime($em));
                $month = $eve . '-%';
            }
            $item = $this->mCapital
                ->where(['dd_user_id' => $this->dd_user_id, 'type' => 1, 'create_time' => ['like', $month]])
                ->sum('amount');
            if (!empty($item) && $item) {
                $list[] = [
                    'year' => substr($month, 0, 4),
                    'month' => substr($month, 5, 2),
                    'amount' => $item
                ];
            }
        }
        return $list;
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 17:26
     * @description 用户申请提现
     * @param int $amount 总金额
     * @param string $remark 备注
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getWorkWithdraw($amount = 0, $remark = '')
    {
        if ($amount <= 0) {
            return -1;
        }
        $now_user = $this->dd_user_id;
        if (!$now_user) {
            return -1;
        }
        $user = $this->mUser
            ->where(['dd_user_id' => $now_user])
            ->find();
        if (empty($user)) {
            return -2;
        }
        if (!($user['account_code'] && $user['account_user'])) {
            return -4;
        }
        // 获取提现相关配置
        $obj = new TransferConfigService();
        $config = $obj->getWithdrawConfig();
        if (($config['guaranteed_cash_withdrawal'] > 0) && ($user['capital'] < $config['guaranteed_cash_withdrawal'])) {
            return -7;
        }
        if ($user['capital'] < $amount) {
            return -3;
        }
        // 限制次数
        if ($config['days_between_withdrawals'] > 0) {
            $last_log = $this->mCapital->where(['dd_user_id' => $now_user, 'type' => 2])->order('id desc')->find();
            if ($last_log) {
                // 判断时间间隔
                $last_time = strtotime($last_log['create_time']) + $config['days_between_withdrawals'] * 86400;
                if ($last_time > time()) {
                    return -5;
                }
            }
        }
        // 限制金额
        if (($config['maximum_single_cash_withdrawal'] > 0) && ($amount > $config['maximum_single_cash_withdrawal'])) {
            return -8;
        }
        // 修改用户账号余额
        $capital_update = [
            'capital' => ($user['capital'] -  $amount)
        ];
        $now_time = date('Y-m-d H:i:s');
        $now_user = $this->dd_user_id;
        $now_user_name = get_user_name($now_user);
        $status_remark = $now_user_name . '于' . $now_time . '添加了提现记录单;';
        // 添加新的余额记录
        $capital_insert = [
            'dd_user_id' => $this->dd_user_id,
            'type' => 2,
            'amount' => $amount,
            'status' => 2,
            'account_code' => $user['account_code'],
            'account_user' => $user['account_user'],
            'create_time' => $now_time,
            'create_user' => $now_user,
            'status_remark' => $status_remark,
            'remark' => $remark,
        ];
        try {
            Db::startTrans();
            $res1 = $this->mUser
                ->where(['dd_user_id' => $now_user])
                ->update($capital_update);
            $res2 = $this->mCapital
                ->insert($capital_insert);
            if ($res1 && $res2) {
                Db::commit();
                return 1;
            } else {
                Db::rollback();
                return 0;
            }
        } catch (\Exception $exception) {
            Db::rollback();
            return 0;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 21:33
     * @description 获取组长列表
     * @param $param
     * @return bool|false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLeaderList($param)
    {
        // 暂时不使用页码
        $dept_id = session('dept_id');
        $list = $this->mUser
            ->where(['level' => 2, 'dept_id' => $dept_id])
            ->select();
        return $list;
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 21:43
     * @description 移除领导
     * @param int $user_id
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function removeLeader($user_id = 0)
    {
        if (!$user_id) {
            return -1;
        }
        $user = $this->mUser
            ->where(['dd_user_id' => $user_id])
            ->find();
        if (empty($user)) {
            return -2;
        }
        if ($user['level'] != 2) {
            return -3;
        }
        $dept_id = session('dept_id');
        if ($dept_id != $user['dept_id']) {
            return -4;
        }
        // TODO 判断该组长有没有需要做的
        $res = $this->mUser->where(['dd_user_id' => $user_id])->update(['level' => 3, 'dept_id' => 0]);
        if ($res) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 22:19
     * @description 添加组长
     * @param array $user_array
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addLeader($user_array = [])
    {
        $mUser = $this->mUser;
        $dept_id = session('dept_id');
        if (empty($user_array)) {
            // 移除所有组长
            $mUser->where(['level' => 2, 'dept_id' => $dept_id])->update(['level' => 3, 'dept_id' => 0]);
            return 1;
        } else {
            $new_box = [];
            $update_box = [];
            // 判断用户数据库中是否存在， ①有的话看用户等级，需要修改等级的修改 ②数据库中没有的从钉钉中查询添加
            foreach ($user_array as $item) {
                $temp_user = $mUser->where(['dd_user_id' => $item])->find();
                if (empty($temp_user)) {
                    $user_info = $this->DingtalkService->getUserInfoByDDUserId($item);
                    if (empty($user_info)) {
                        return -2;
                    } else {
                        $new_box[] = [
                            'dd_user_id' => $item,
                            'name' => $user_info['name'],
                            'avatar' => $user_info['avatar'],
                            'level' => 2,
                            'dept_id' => $dept_id
                        ];
                    }
                } else {
                    if ($temp_user['level'] == 1) {
                        return -4;
                    }
                    if ($temp_user['level'] == 2) {
                        continue;
                    }
                    $update_box[] = $item;
                }
            }
            if (empty($new_box) && empty($update_box)) {
                return -3;
            }
            try {
                Db::startTrans();
                $res0 = $mUser->where(['level' => 2, 'dept_id' => $dept_id])->update(['level' => 3, 'dept_id' => 0]);
                if (empty($new_box)) {
                    $res1 = 1;
                } else {
                    $res1 = $mUser->insertAll($new_box);
                }
                if (empty($update_box)) {
                    $res2 = 1;
                } else {
                    $res2 = $mUser->where(['dd_user_id' => ['in', $update_box]])->update(['level' => 2, 'dept_id' => $dept_id]);
                }
                if ($res1 && $res2) {
                    Db::commit();
                    return 1;
                } else {
                    Db::rollback();
                    return 0;
                }
            } catch (\Exception $exception) {
                Db::rollback();
                return 0;
            }
        }


    }

    /**
     * @auther zlq
     * @create_time 2020/5/20 22:22
     * @description 编辑用户银行账号
     * @param int $user_id 用户ID
     * @param string $account_code 银行账号
     * @param string $account_user 银行账号人名
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function editUserAccountCode($user_id = 0, $account_code = '', $account_user = '')
    {
        if (!$user_id) {
            return -1;
        }
        if (!$account_code) {
            return -1;
        }
        if (!$account_user) {
            return -1;
        }
        $user = $this->mUser
            ->where(['dd_user_id' => $user_id])
            ->find();
        if (empty($user)) {
            return -2;
        }
        if (($user['account_code'] == $account_code) &&($user['account_user'] && $account_user)) {
            return -3;
        }
        $res = $this->mUser
            ->where(['dd_user_id' => $user_id])
            ->update(['account_code' => $account_code, 'account_user' => $account_user]);
        if ($res) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/23 10:59
     * @description 获取不可选部门
     * @return array
     */
    public function getNotCheckDeptList()
    {
        $all_dept = $this->DingtalkService->getAllDeptList();
        if (empty($all_dept)) {
            return [];
        } else {
            $use_dept = config('dic.use_dept');
            // 增加 340698980  // 包装车间工人
            $add = $this->DingtalkService->getNextGradeDeptList(340698980);
            if (!empty($add)) {
                foreach ($add as $one) {
                    $use_dept[] = $one;
                }
            }
            $not_box = [];
            foreach ($all_dept as $dept) {
                if (!in_array($dept['id'], $use_dept)) {
                    $not_box[] = $dept['id'];
                }
            }
            return $not_box;
        }
    }

    /**
     * @auther zlq
     * @create_time 2020/5/23 11:27
     * @description 获取不可选部门不可选用户
     * @return array
     */
    public function getNotCheckUserList()
    {
        $cant_use_dept = config('dic.user_cant_user_dept');
        if (empty($cant_use_dept)) {
            return [];
        } else {
            $user_box = [];
            foreach ($cant_use_dept as $item) {
                $user_list = $this->DingtalkService->getDeptUserList($item);
                if (!empty($user_list)) {
                    $user_box = array_merge($user_box, $user_list);
                }
            }
            return $user_box;
        }
    }
}